﻿#region

using System;

#endregion

namespace TSharp.Core.Message.MessageImpl
{
    /// <summary>
    ///     消息注册句柄实现
    ///     <para>by tangjingbo at 2009/12/14 21:38</para>
    /// </summary>
    /// <typeparam name="TMessage">The type of the message.</typeparam>
    internal class RegisterHandle<TMessage> : IRegisterHandle<TMessage>
    {
        public RegisterHandle(IHandle<TMessage> listener)
        {
            _listener = new WeakReference(listener);
            _disposed = ListenerDisposed;
            listener.Disposed += _disposed;
        }

        private void ListenerDisposed(object sender, EventArgs e)
        {
            var owner = sender as IHandle;
            if (owner != null)
            {
                owner.Disposed -= _disposed;
            }
            UnRegister();
        }
        private readonly EventHandler _disposed;
        #region IMessageListenerRegHandle<TMessage> 成员

        private static readonly Type messageType = typeof(TMessage);
        private readonly WeakReference _listener;

        private int _order = -1;

        public IHandle<TMessage> GetListener()
        {
            var target = _listener.Target as IHandle<TMessage>;
            return target;
        }

        public Type MessageType
        {
            get { return messageType; }
        }

        public bool IsAlive
        {
            get { return _listener.IsAlive; }
        }

        public bool IsListenSubMessage { get; set; }

        public bool IsListenBubble { get; set; }

        public bool IsListenBroadcast { get; set; }

        public int Order
        {
            get { return _order; }
            internal set { _order = value; }
        }

        public void UnRegister()
        {
            MessageListenerManage.RemoveHandler(this);
        }

        #region IRegisterHandle 成员

        IHandle IRegisterHandle.GetListener()
        {
            return GetListener();
        }

        #endregion

        #endregion

        #region IComparable<IRegisterHandle> 成员

        public int CompareTo(IRegisterHandle other)
        {
            if (other == null)
                return 1;
            return _order.CompareTo(other.Order);
        }

        #endregion
    }
}